// 请求后端，获取并渲染数据
function fetchAndRenderData(page, size) {
    const serverIp = document.getElementById('jobIdInput').value
    const jobDesc = document.getElementById('executorIdInput').value;
    const modifiedBy = document.getElementById('modifiedByInput').value;
    const command = document.getElementById('commandInput').value;

    const url = `/xxl-job-admin/record/search?serverIp=${serverIp}&jobDesc=${jobDesc}&modifiedBy=${modifiedBy}&command=${command}&page=${page}&size=${size}`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            renderTable(data.records); // 渲染表格
            renderPagination(data.page, data.total, data.size); // 渲染分页
        })
        .catch(error => {
            console.error('查询失败:', error);
        });
}

// 渲染表格数据
// 渲染表格数据
function renderTable(records) {
    const tableBody = document.getElementById('modification_record_list').getElementsByTagName('tbody')[0];
    tableBody.innerHTML = ''; // 清空表格内容

    if (records && records.length > 0) {
        // 遍历记录列表并渲染表格行
        records.forEach(record => {
            const row = document.createElement('tr');

            // 格式化修改时间
            const formattedTime = formatDate(record.modificationTime);

            row.innerHTML = `
                <td>${record.serverIp || ''}</td>
                <td>${record.serverUser || ''}</td>
                <td>${record.jobDesc || ''}</td>
                <td>${record.oldSchedule || ''}</td>
                <td>${record.newSchedule || ''}</td>
                <td>${record.oldCommand || ''}</td>
                <td>${record.newCommand || ''}</td>
                <td>${record.modifiedBy || ''}</td>
                <td>${record.reviewedBy || ''}</td>
                <td>${record.ticketNumber || ''}</td>
                <td>${formattedTime || 'N/A'}</td>
            `;
            tableBody.appendChild(row);
        });
    } else {
        // 没有记录时显示提示
        const row = document.createElement('tr');
        row.innerHTML = `<td colspan="10" class="text-center">没有找到相关记录</td>`;
        tableBody.appendChild(row);
    }
}

// 格式化日期
function formatDate(isoString) {
    if (!isoString) return 'N/A';
    const date = new Date(isoString);
    if (isNaN(date.getTime())) return 'N/A'; // 如果不是有效日期

    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


// 渲染分页控件
// 渲染分页控件
function renderPagination(currentPage, totalRecords, pageSize) {
    const totalPages = Math.ceil(totalRecords / pageSize);
    const paginationContainer = document.getElementById('pagination');
    paginationContainer.innerHTML = ''; // 清空分页内容

    // 创建分页信息
    const pageInfo = document.createElement('div');
    pageInfo.classList.add('page-info');
    pageInfo.innerHTML = `第 ${currentPage} 页，共 ${totalPages} 页 <br> 
    当前记录条数 ${Math.min(pageSize, totalRecords - (currentPage - 1) * pageSize)}，共 ${totalRecords} 条`;
    paginationContainer.appendChild(pageInfo);

    // 创建分页按钮的容器
    const paginationControls = document.createElement('div');
    paginationControls.classList.add('pagination-controls', 'text-center', 'mt-2');

    // 创建上一页按钮
    if (currentPage > 1) {
        const prevButton = document.createElement('button');
        prevButton.classList.add('btn', 'btn-default', 'mr-2');
        prevButton.textContent = '上一页';
        prevButton.addEventListener('click', () => {
            fetchAndRenderData(currentPage - 1, pageSize);
        });
        paginationControls.appendChild(prevButton);
    }

    // 创建下一页按钮
    if (currentPage < totalPages) {
        const nextButton = document.createElement('button');
        nextButton.classList.add('btn', 'btn-default', 'ml-2');
        nextButton.textContent = '下一页';
        nextButton.addEventListener('click', () => {
            fetchAndRenderData(currentPage + 1, pageSize);
        });
        paginationControls.appendChild(nextButton);
    }

    paginationContainer.appendChild(paginationControls);
}


// 初始化页面时，加载第一页的数据
document.getElementById('searchBtn').addEventListener('click', function () {
    const pageSize = parseInt(document.getElementById('recordsPerPage').value) || 10;
    fetchAndRenderData(1, pageSize);
});

// 监听分页条数选择框的变化
document.getElementById('recordsPerPage').addEventListener('change', function () {
    const pageSize = parseInt(this.value) || 10;
    fetchAndRenderData(1, pageSize); // 页数变更时重置为第一页
});

// 默认加载第一页的数据
fetchAndRenderData(1, 10);
